package com.sunchangming.rpcgen;

import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class BeanConverter implements Converter {

	@SuppressWarnings("rawtypes")
	@Override
	public boolean canConvert(Class clazz) {
		return clazz.equals(Bean.class);
	}

	@Override
	public void marshal(Object arg0, HierarchicalStreamWriter arg1, MarshallingContext arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
		final Bean ns = new Bean();
		ns.name = reader.getAttribute("name");
		if (ns.name != null)
			ns.name.trim();
		final String codeStr = reader.getAttribute("code");
		if (codeStr != null)
			codeStr.trim();
		ns.sqltable = reader.getAttribute("sqltable");
		if (ns.sqltable != null)
			ns.sqltable.trim();
		ns.key = reader.getAttribute("key");
		if (ns.key != null)
			ns.key.trim();
		
		ns.baseclass = reader.getAttribute("baseclass");
		if (ns.baseclass != null)
			ns.baseclass.trim();
		
		if (codeStr == null || codeStr.isEmpty())
			ns.code = -1;
		else
			ns.code = Integer.valueOf(codeStr);
		while (reader.hasMoreChildren()) {
			reader.moveDown();
			try {
				if ("variable".equals(reader.getNodeName())) {
					final Variable ns1 = (Variable) context.convertAnother(ns, Variable.class);
					ns1.parent = ns;
					ns.vars.add(ns1);
				} else
					throw new ConversionException("不认识的节点" + reader.getNodeName());
			} finally {
				reader.moveUp();
			}
		}
		return ns;
	}
}
